<?php

namespace backend\controllers;

use backend\models\Baseproducts;
use yii\web\UploadedFile;
use yii;

class WebuiController extends CommonController
{
    public function actionAjaxUpload()
    {
        $post = yii::$app->request->post();
        if (yii::$app->request->isPost){
            if (is_null($post['uploadExt']) || is_null($post['file_id'])){
                return $this->renderJson(['statusCode' => 401, 'message' => '操作失败，未授权请求']);
            }
            $temp = UploadedFile::getInstanceByName('file_data');
            if ($temp){
                $path='uploaded/';
                if(!file_exists($path)){
                    mkdir($path);
                }
                if(!file_exists($path.$post['uploadExt'])){
                    mkdir($path.$post['uploadExt']);
                }
                $random = yii::$app->security->generateRandomString().time();
                $filename = md5($random) . $post['file_id'] . '.' . $temp->getExtension();
                $savepath = $path.$post['uploadExt'].'/'.$filename;
                if($temp->saveAs($savepath)){
                    $data = [
                        'filename'=> yii::$app->params['staticUrl'].'/'.$savepath,
                        'filepath' => '/'.$savepath,
                        'formerly' => $_FILES['file_data']['name'],
                    ];
                    return $this->renderJson([
                        'statusCode' => 200,
                        'message' => '操作成功',
                        'data' => $data
                    ]);
                }
                return $this->renderJson(['statusCode' => 300, 'message' => '操作失败']);
            }
            return $this->renderJson(['statusCode' => 300, 'message' => '操作失败']);
        }
        return $this->renderJson(['statusCode' => 401, 'message' => '操作失败，未授权请求']);
    }


    public function actionRemoveUploaded()
    {
        $path = yii::getAlias('@backend').'/web';
        $post = yii::$app->request->post();
        if (is_null($post['files']) || empty($post['files'])){
            return $this->renderJson(['statusCode' => 300, 'message' => '操作失败，没有删除任何文件']);
        }
        $arrProduct = json_decode($post['files']);
        $iCount = 0;
        foreach ($arrProduct as $k => $value){
            $filepath = $value->filepath;
            if (is_file($path.$filepath)){
                unlink($path.$filepath);
                $iCount += 1;
            }
        }
        return $this->renderJson(['statusCode' => 200, 'message' => '操作成功，成功删除'.$iCount.'个文件']);
    }

}
